package com.qf.common.configure;

import cn.hutool.core.util.StrUtil;
import lombok.Data;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpHost;
import org.apache.http.NameValuePair;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.BasicCredentialsProvider;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author claud
 * 2018年8月15日17:47:52
 * httpclient的所需参数类
 */
@Data
public class HttpClientConfig {

    public static final String USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.9 Safari/537.36";
    /**
     * 默认的超时时间--wos的一般时间都很长，需要设置为25000
     */
    public int TIME_OUT = 10000;
    private static Integer bdIpIndex = 0;
    /**
     * post请求参数
     */
    List<NameValuePair> nvpsList;
    /**
     * 请求配置
     */
    private RequestConfig requestConfig;
    /**
     * 代理请求配置
     */
    private CredentialsProvider credsProvider;
    private Map<String, String> headerMap = new HashMap<>();
    private String refer;
    private String host;
    /**
     * 存储空间路径
     */
    private String storagePath;
    private BasicCookieStore cookieStore = new BasicCookieStore();
    /**
     * 特殊cookie
     */
    private String cookie;
    /**
     * 需要跳转的地址
     */
    private String url;

    public HttpClientConfig() {
        super();
        this.requestConfig = createRequestConfigure(null, null, null, TIME_OUT, true);
    }


    /**
     * 通过代理信息生成相应的检索配置信息
     */
    public HttpClientConfig(ProxyInfo pi, String url, String refer, boolean redireFlag) {
        super();
        this.refer = refer;
        this.url = url;

        if (!StrUtil.isEmpty(refer)) {
            this.headerMap.put(HttpHeaders.REFERER, refer);
        }
        if (pi != null && (pi.getSwitchType() == null || pi.getSwitchType().equals("1"))) {
            this.credsProvider = createCredentials(pi);
        }
        String remoteIp = null;
        Integer remotePort = 0;
        if (pi != null && !StrUtil.isEmpty(pi.getIp())) {
            remoteIp = pi.getIp();
            remotePort = Integer.parseInt(pi.getPort());
        }
        this.requestConfig = createRequestConfigure(remoteIp, remotePort, null, TIME_OUT, redireFlag);
    }

    public HttpClientConfig(ProxyInfo pi, String url, String refer, boolean redireFlag, int Timeout) {
        super();
        this.refer = refer;
        this.url = url;

        if (!StrUtil.isEmpty(refer)) {
            this.headerMap.put(HttpHeaders.REFERER, refer);
        }
        if (pi != null && (pi.getSwitchType() == null || pi.getSwitchType().equals("1"))) {
            this.credsProvider = createCredentials(pi);
        }
        String remoteIp = null;
        Integer remotePort = 0;
        if (pi != null && !StrUtil.isEmpty(pi.getIp())) {
            remoteIp = pi.getIp();
            remotePort = Integer.parseInt(pi.getPort());
        }
        this.requestConfig = createRequestConfigure(remoteIp, remotePort, null, Timeout, redireFlag);
    }

    public static void main(String[] args) {
        HttpClientConfig config = new HttpClientConfig(ProxyInfo.getShangjiaoIpProxy(), "", "11", true);
        System.out.println(config);
        System.out.println(config.getRequestConfig());

    }

    /**
     * 生成用户凭证的方法,代理的用户账号和密码
     */
    private static CredentialsProvider createCredentials(ProxyInfo pi) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
//        credsProvider.setCredentials(new AuthScope(pi.getIp(), Integer.parseInt(pi.getPort())), (Credentials) new UsernamePasswordCredentials(pi.getUserName(), pi.getPassword()));
        return credsProvider;
    }

//    private void setQfDefaultCookie(){
//        String mycookie="uid:57496;gid:18;";
//        String mycookiestr=AuthCode.authcodeEncode(mycookie, "qf3.1415");
////        Cookie cookie = new Cookie("userinfo", mycookiestr);
//        String cookie = "userinfo="+ mycookiestr+";";
////        httpget.addHeader("cookie","userinfo="+ mycookiestr+";");
//        this.setCookie(cookie);
//    }

    /**
     * 生成代理ip的请求配置的方法
     * ConnectionTimeout是tcp连接建立的时间--即tcp三次握手完成时间.
     * SocketTimeout是连接建立后,数据传输过程中数据报之间间隔的最大时间.
     * localAdd是多ip的主机的不同出口ip
     */
    public static RequestConfig createRequestConfigure(String remoteIp, Integer remotePort, String localAdd, int timeOut, Boolean redirectFlag) {
        HttpHost host = null;
        if (!StrUtil.isEmpty(remoteIp)) {
            host = new HttpHost(remoteIp, remotePort);
        }
        InetAddress adds = null;
        if (localAdd != null) {
            try {
                adds = InetAddress.getByName(localAdd);
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
        }
        RequestConfig requestConfig = RequestConfig.custom()
//                .setCookieSpec(CookieSpecs.STANDARD)
                .setSocketTimeout(timeOut)
                .setConnectTimeout(timeOut)
                .setRedirectsEnabled(redirectFlag)
                .setProxy(host)
                .setLocalAddress(adds)
                .build();
        return requestConfig;
    }


    /**
     * 初始化方法
     */
    public static void init() {
//        try {
//            ClassLoader classLoader = HttpClientConfig.class.getClassLoader();
//            /**解析百度vps的ip地址*/
//            URL resource = classLoader.getResource("baidu-ip.txt");
//            String path = resource.getPath();
//            List<String> baiduList = FileUtil.readFile2List(path, "utf-8");
//            Iterator<String> it = baiduList.iterator();
//            while(it.hasNext()){
//                if(it.next().startsWith("#")){
//                    it.remove();
//                }
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
    }

}
